<template>
  <el-table
    class="troila-table"
    ref="table"
    :data="data"
    v-loading="loading"
    :cell-class-name="cellClass"
    :tree-props="{ children: children }"
    :row-key="rowKey ? rowKey : 'id'"
    :default-expand-all="treeFold"
    tooltip-effect="dark troila-table-tooltip"
    @selection-change="handleSelectionChange"
    @sort-change="sortChange"
    @expand-change="expandChange"
  >
    <el-table-column
      v-if="selection && !(children || rowKey)"
      prop="selection"
      type="selection"
      width="80"
    ></el-table-column>
    <el-table-column
      v-if="index && !(children || rowKey)"
      prop="index"
      type="index"
      :index="getIndex"
      label="序号"
      width="80"
    ></el-table-column>
    <el-table-column
      :prop="item.code"
      :label="item.label"
      :sortable="item.sort"
      :show-overflow-tooltip="item.tooltip"
      v-for="(item, i) in title"
      :key="item.code"
      :min-width="item.width ? item.width : null"
      :class-name="i == 0 && children ? 'textLeft' : ''"
    >
      <template slot-scope="scope">
        <span :style="getStyle(item, scope.row)">{{
          item.format
            ? item.format(scope.row, item.code)
            : item.dict && dictionary[item.dict]
            ? getdictName(
                typeof scope.row[item.code] == 'string'
                  ? scope.row[item.code].split(',')
                  : scope.row[item.code],
                dictionary[item.dict]
              )
            : ishasValue(scope.row, item.code)
        }}</span>
      </template>
    </el-table-column>
    <el-table-column
      prop="operation"
      label="操作"
      :width="operaWidth"
      fixed="right"
      v-if="data.length > 0 && operation.length > 0"
    >
      <template slot-scope="scope">
        <el-tooltip
          class="item"
          effect="dark"
          placement="top"
          :content="
            item.label ? item.label : defaultBtn[item.code ? item.code : item]
          "
          v-for="item in operation"
          :key="item.code ? item.code : item"
          :enterable="false"
        >
          <el-button
            type="text"
            @click="btnClick(scope.row, item.code ? item.code : item)"
            v-limit="item.limit"
            v-show="item.show ? item.show(scope.row) : true"
            :style="{
              margin: (item.show ? item.show(scope.row) : true) ? null : 0,
            }"
            :disabled="
              (item.show ? item.show(scope.row) : true)
                ? item.disabled
                  ? item.disabled(scope.row)
                  : false
                : true
            "
          >
            <unit-icon
              class="troila-icon"
              :type="item.code ? item.code : item"
              :disabled="item.disabled ? item.disabled(scope.row) : false"
              :color="item.color ? item.color : colors[color]"
          /></el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import unitOver from './over'
export default {
  name: 'unitTable',
  components: { unitOver },
  props: {
    // loading
    loading: {
      type: Boolean,
      default: false,
    },
    // 是否显示多选框
    selection: {
      type: Boolean,
      default: false,
    },
    // 是否显示序号
    index: {
      type: Boolean,
      default: false,
    },
    // 树形的children 为空则非树形
    children: {
      type: String,
      default: null,
    },
    // row-key唯一主键 为空则非树形
    rowKey: {
      type: String,
      default: null,
    },
    // 展开收起tree
    treeFold: {
      type: Boolean,
      default: false,
    },
    // 表头
    title: {
      type: Array,
      default() {
        return []
      },
    },
    // 表格数据
    data: {
      type: Array,
      default() {
        return []
      },
    },
    // 表格操作
    operation: {
      type: Array,
      default() {
        return []
      },
    },
    // 操作按钮个数
    opera: {
      type: Number,
    },
    // 数据字典
    dictionary: {
      type: Object,
      default() {
        return {}
      },
    },
    // 页码
    page: {
      type: Number,
    },
    // 条数
    limit: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      defaultBtn: {
        detail: '查看',
        add: '添加',
        edit: '修改',
        delete: '删除',
      },
      treeFold_: this.treeFold,
      open: this.treeFold ? [...this.foldRows(this.data)] : [],
      pageNum: this.page ? this.page - 1 : 0,
      once: true,
      colors: {
        gray: '#3C6995',
        green: '#18AB9A',
        orange: '#FF9B57',
        red: '#4B5071',
        black: '#4B5071',
        purple: '#4B5071',
      },
    }
  },
  computed: {
    operaWidth() {
      return (this.opera ? this.opera : this.operation.length) * 36 + 50
    },
    color() {
      return this.$store.state.color
    },
  },
  watch: {
    treeFold() {
      let open = [...this.open]
      // console.log(open)
      this.foldRows(this.data, open.length > 0 ? false : true)
      open.length > 0
        ? (this.open = [])
        : (this.open = [...this.foldRows(this.data)])
    },
    data: {
      deep: true,
      handler() {
        this.pageNum = this.page ? this.page - 1 : 0
        if (this.once) {
          this.once = false
          this.open = this.treeFold ? [...this.foldRows(this.data)] : []
        } else {
          this.treeFold_
            ? (this.open = [...this.foldRows(this.data, true)])
            : (this.foldRows(this.data, false), (this.open = []))
          // console.log(this.open)
        }
      },
    },
  },
  methods: {
    getStyle(item, row) {
      if (item.style && typeof item.style == 'object') {
        let style = {}
        for (let k in item.style) {
          item.style[k].result == row[item.code]
            ? (style[k] = item.style[k].value)
            : null
        }
        return style
      }
    },
    foldRows(data, j) {
      let arr = []
      for (let i in data) {
        let v = data[i]
        let children = !this.children
          ? []
          : v[this.children]
          ? v[this.children]
          : []
        if (children.length > 0) {
          j !== undefined ? this.$refs.table.toggleRowExpansion(v, j) : null
          arr.push(v[this.rowKey ? this.rowKey : 'id'])
          // arr = [...arr, ...this.foldRows(children, j)]
          this.foldRows(children, j)
        }
      }
      return arr
    },
    cellClass({ row, column, rowIndex, columnIndex }) {
      // console.log(row, column, rowIndex, columnIndex)
      if (column.property === 'operation') {
        return 'operation-cell'
      }
    },
    expandChange(row, expanded) {
      if (this.open.indexOf(row[this.rowKey ? this.rowKey : 'id']) > -1) {
        this.open.splice(
          this.open.indexOf(row[this.rowKey ? this.rowKey : 'id']),
          1
        )
      } else if (
        this.foldRows(this.data).indexOf(
          row[this.rowKey ? this.rowKey : 'id']
        ) > -1
      ) {
        this.open.push(row[this.rowKey ? this.rowKey : 'id'])
      }
    },
    btnClick(row, code) {
      this.$emit('return', code, { row })
    },
    sortChange({ column, prop, order }) {
      this.$emit('return', 'sort', { column, prop, order })
    },
    handleSelectionChange(selection) {
      this.$emit('return', 'selection', { selection })
    },
    getIndex(index) {
      return (
        (this.pageNum ? Number(this.pageNum) * this.limit + index : index) + 1
      )
    },
  },
}
</script>
<style scoped>
/* .troila-table {
  border: 1px solid #ebeef5;
  border-bottom: none;
} */
.troila-table >>> .operation-cell {
  font-size: 0;
}
.troila-table >>> .operation-cell > .cell {
  margin-right: -16px;
}
.troila-table >>> .operation-cell .el-button:hover {
  opacity: 0.8;
}
</style>
